// 初始化数据
const initState = {
  // 订单列表
  list: [
    {id: 1, name: '手机'},
    {id: 2, name: '电脑'},
  ]
}

// 统一处理action的type
const type = {
  CHANGELIST: 'changList',
  ADDLIST: 'addList',
  DELLIST: 'delList',
}

// 统一处理action，这里会生成所有的action
export const actions = {
  changeList: (list) => ({type: type.CHANGELIST, list}),
  addList: (list) => ({type: type.ADDLIST, list}),
  delList: (index) => ({type: type.DELLIST, index}),
}

const reducer = (state = initState, action)=> {
  switch (action.type) {
    case type.CHANGELIST:
      return {
        ...state,
        list: action.list
      }
    case type.ADDLIST:
      // 添加订单
      return {
        ...state,
        // 组件中传的是数组，所以用concat；如果是对象，就push
        list: state.list.concat(action.list)
      }
    case type.DELLIST:
      // 通过一个临时变量，深拷贝源数据
      let tepmList = [...state.list];
      // splice会修改原数组，返回删除的片段
      tepmList.splice(action.index.index, 1)
      return {
        ...state,
        list: tepmList
      }
    default:
      return state
  }
}
export const getList = (state) => (state.order.list);
export default reducer;